package com.luocc.ccdemo.ui

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.luocc.ccdemo.R
import com.luocc.ccdemo.common.BlogListAdapter
import com.luocc.ccdemo.common.OnItemClickListener
import com.luocc.ccdemo.entity.Blog
import com.luocc.ccdemo.vm.BlogViewModel

/**
 * 首页，展示博客
 */
class HomeFragment : Fragment() {
    private var curPage: Int = 0
    private var mLoadingFinished = false
    private lateinit var mContext: Context
    private lateinit var mBlogList: RecyclerView
    private lateinit var mViewModel: BlogViewModel
    private lateinit var mAdapter: BlogListAdapter
    private lateinit var mLayoutManager: LinearLayoutManager

    private val mScrollListener: RecyclerView.OnScrollListener = object :
        RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            Log.d(TAG, "onScrollStateChanged 1: ${mLayoutManager.itemCount}")
            if (mLoadingFinished) {
                val position = mLayoutManager.findLastVisibleItemPosition()
                Log.d(TAG, "onScrollStateChanged 2: $position")
                if (position + 3 > mLayoutManager.itemCount) {
                    // 去加载新的list，但是要防止重复加载
                    mLoadingFinished = false
                    mViewModel.getBlog(curPage + 1)
                }
            }
        }
    }

    private val mItemClickListener = object : OnItemClickListener<Blog> {
        override fun onClick(position: Int, obj: Blog) {
            // webView有些网站只能加载出来一个框是怎么回事?
            val uri = Uri.parse(obj.url)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        }
    }


    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mAdapter = BlogListAdapter(mContext)
        mAdapter.setOnItemClickListener(mItemClickListener)
        mViewModel = ViewModelProvider(this).get(BlogViewModel::class.java)
        mViewModel.getBlogList().observe(this) {
            mLoadingFinished = true
            if (it.code == 0) {
                it.data?.let { data ->
                    curPage = data.getInt("curPage")
                    val blogs = data.getParcelableArrayList<Blog>("blogs")
                    if (!blogs.isNullOrEmpty()) {
                        Log.d(TAG, "onCreate: ${blogs.size}")
                        val newList = ArrayList(mAdapter.currentList)
                        newList.addAll(blogs)
                        mAdapter.submitList(newList)
                    }

                }
            }
        }
        Log.d(TAG, "onCreate")
        mViewModel.getBlog()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val parent = inflater.inflate(R.layout.fragment_home, container, false)
        mBlogList = parent.findViewById(R.id.blogs)
        mBlogList.adapter = mAdapter
        mLayoutManager = LinearLayoutManager(mContext)
        mBlogList.layoutManager = mLayoutManager
        mBlogList.addOnScrollListener(mScrollListener)
        return parent
    }

    companion object {
        private const val TAG = "LC_HomeFragment"
    }
}